﻿@inject ModalService ModalService

<Input @bind-Value="@value" Placeholder="user name" />
<br />
<br />
<Button OnClick="OpenTemplate" Type="ButtonType.Primary">Use Template</Button>
<br />
<br />
<Button OnClick="OpenTemplateWithResult" Type="ButtonType.Primary">Use Template With Result</Button>

@code{

    private string value = "blazor";

    private ModalRef _modalRef;

    private async Task OpenTemplate()
    {
        var templateOptions = new Form.demo.Basic.Model();
        templateOptions.Username = value;

        var modalConfig = new ModalOptions();
        modalConfig.Title = "Basic Form";
        modalConfig.OnCancel = async (e) =>
        {
            Console.WriteLine("OnCancel");
            await _modalRef.CloseAsync();
        };

        modalConfig.AfterClose = () =>
        {
            Console.WriteLine("AfterClose");
            value = templateOptions.Username;
            InvokeAsync(StateHasChanged);
            return Task.CompletedTask;
        };

        _modalRef = await ModalService
            .CreateModalAsync<ModalTemplateDemo, Form.demo.Basic.Model>
            (modalConfig, templateOptions);

        _modalRef.OnOpen = () =>
        {
            Console.WriteLine("ModalRef OnOpen");
            return Task.CompletedTask;
        };

        _modalRef.OnOk = () =>
        {
            Console.WriteLine("ModalRef OnOk");
            return Task.CompletedTask;
        };

        _modalRef.OnCancel = () =>
        {
            Console.WriteLine("ModalRef OnCancel");
            return Task.CompletedTask;
        };

        _modalRef.OnClose = () =>
        {
            Console.WriteLine("ModalRef OnClose");
            return Task.CompletedTask;
        };
    }


    private async Task OpenTemplateWithResult()
    {
        var modalConfig = new ModalOptions();
        modalConfig.Title = "TemplateWithResult";
        modalConfig.Style = "top:20px;";
        // In order for Dispose in ConfirmTemplateDemo to take effect every time it is closed
        modalConfig.DestroyOnClose = true;

        var modalRef = await ModalService.CreateModalAsync<ConfirmTemplateDemo, string, string>(modalConfig, value);

        modalRef.OnOk = (result) =>
        {
            Console.WriteLine($"OnOk:{result}");
            return Task.CompletedTask;
        };

        modalRef.OnCancel = (result) =>
        {
            Console.WriteLine($"OnCancel:{result}");
            return Task.CompletedTask;
        };
    }

}